use async_trait::async_trait;
use clap::Parser;

use crate::commands::commands::Command;
use crate::models::models;
use crate::models::models::command::CommandState;
use crate::utils::command;

#[derive(Debug, Default, Clone, Parser)]
#[clap(disable_help_flag = true)]
struct Args {
    // 解码
    #[arg(short = 'd', long = "decode", default_value_t = false)]
    decode: bool,
    // 字符串
    value: String,
}

#[derive(Debug, Default, Clone)]
pub(crate) struct UrlCommand {}

#[async_trait]
impl Command for UrlCommand {
    async fn execute(&self, command: models::command::Command) -> models::command::Command {
        let args = command::parse_command_args::<Args>(command.args.as_str());
        if args.is_err() {
            return self.save_command_output(command, CommandState::Success, args.unwrap_err().to_string());
        }

        let args = args.unwrap();

        if args.decode {
            let content = urlencoding::decode(args.value.as_str());
            if content.is_err() {
                return self.save_command_output(command, CommandState::Failed, format!("解码失败: {}", content.unwrap_err().to_string()));
            }

            return self.save_command_output(command, CommandState::Success, content.unwrap().to_string());
        }

        self.save_command_output(command, CommandState::Success, urlencoding::encode(args.value.as_str()).to_string())
    }
}